<?php

namespace App\Admin\Controllers\User;

use App\Admin\Models\AdminPermission;
use App\Admin\Models\AdminRole;
use Illuminate\Http\Request;
use App\Admin\Controllers\Controller;

class RoleController extends Controller
{
    // 用户列表
    public function index()
    {
        $roles = AdminRole::query()->paginate(10);
        return view('admin.role.index', compact('roles'));
    }

    // 创建用户页面
    public function create()
    {
        return view('admin.role.create');
    }

    // 创建用户行为
    public function store(Request $request)
    {
        // 验证
        $rules = [
            'name' => 'required|string|min:2',
            'description' => 'required|string|min:2',
        ];
        $this->validate($request, $rules);

        // 保存
        AdminRole::query()->create($request->only('name', 'description'));

        // 渲染
        return redirect('/admin/roles');
    }
    
    public function permissions(AdminRole $role)
    {
        // 所有的权限
        $permissions = AdminPermission::all();

        // 角色的权限
        $rolePermissions = $role->permissions;

        return view('admin.role.permissions', compact('permissions', 'rolePermissions', 'role'));
    }

    public function storePermissions(Request $request, AdminRole $role)
    {
        $rules = [
            'permissions' => 'required|array',
        ];
        $this->validate($request, $rules);

        $newPermissions = AdminPermission::query()->findMany($request->input('permissions'));
        $oldPermissions = $role->permissions;

        // 要增加的
        $addPermissions = $newPermissions->diff($oldPermissions);
        // 要删除的
        $deletePermissions = $oldPermissions->diff($newPermissions);

        foreach ($addPermissions as $permission) {
            $role->assignPermission($permission);
        }
        foreach ($deletePermissions as $permission) {
            $role->deletePermission($permission);
        }

        return redirect('/admin/roles');
    }
}
